﻿angular.module("umbraco").controller("UE.DealerListController",
    function ($scope, $routeParams, dealerResource, navigationService, dialogService, notificationsService ) {
        var vm = this;
        var key = $routeParams.id;
        var pageSize = 20;
        vm.dealers = [];
        vm.loading = false;
        vm.overlay = {
            show: false,
            title:"geocodering",
            hideSubmitButton: true,
            closeButtonLabelKey: "actions_cancel",
            close: function () {
                vm.overlay.show = false;
                vm.loading = false;
            }
        };

        vm.pagination = {
            pageNumber: 1,
            totalPages: 1,
            nextPage: function (pageNumber) {
                getDate(pageNumber);
            },
            prevPage: function (pageNumber) {
                getDate(pageNumber);
            },
            goToPage: function (pageNumber) {
                getDate(pageNumber);
            }
        }

        dealerResource.findAll(key, 1, pageSize, "").then(function (response) {
            vm.dealers = response.Dealers;
            vm.pagination.pageNumber = response.CurrentPage;
            vm.pagination.totalPages = response.PageCount;
            navigationService.syncTree({
                tree: 'dealerListAlias',
                path: response.Path,
                forceReload: true,
                activate: true
            });
        });

        var getDate = function (index) {
            dealerResource.findAll(key, index, pageSize, "").then(function (response) {
                vm.dealers = response.Dealers;
                vm.pagination.pageNumber = response.CurrentPage;
                vm.pagination.totalPages = response.PageCount;
            });
        };

        $scope.geocoder = function (id) {
            console.log(id);
            vm.overlay.show = true;
            vm.loading = true;
            dealerResource.geocoder(id).then(function (response) {
                vm.loading = false;
                vm.overlay.show = false;
                if (response.ErrorCode == 0) {
                    notificationsService.success("Geocoder success", "Geocoder success, reload data!");
                    getDate(vm.pagination.pageNumber);
                } else {
                    notificationsService.error("Geocoder Failed", "Geocoder failed, please try again!");
                }
            });
        };

        $scope.delete = function (id) {
            dialogService.open({
                template: "/App_Plugins/DealerSection/Modal/delete.html",
                dialogData: id,
                callback: function (data) {
                    if (data) {
                        getDate(vm.pagination.pageNumber);
                    }
                }
            });
        };
    }
);